package com.example.nna.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nna.parserhtml.parser;
import com.example.nna.util.UserInfo;

public class Page extends Activity{
	static final String URL="http://vozforums.com/";
	public static final int TASK_GETDOC = 0;
	public static final int TASK_LOGIN = 1;
	public static final int TASK_LOGOUT = 2;
	
	public static final int GO_INDEXPAGE = 0;
	public static final int GO_REFRESH = 1;
	public static final int GO_NEXT = 2;
	public static final int GO_PREVIOUS = 3;
	public static final int GO_FIRST = 4;
	public static final int GO_LAST = 5;
	
	public static final double FONTSCALE_MIN = 0.5;
	public static final double FONTSCALE_MAX = 2.5;
	
	public static int width;
	public static int height;
	
	Context mContext;
	Activity mActivity;
	ListView mList;
	ImageButton mMenuLogin;
	ImageButton mMenuFont;
	TextView mMenuTitle;
	Document doc;
	UserInfo mUser;
	float mTextSize;
    TaskGetHtml mTask;
	protected parser mParser;
	//protected Bitmap bitmap1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initUI();
		getRevolution();
		mTextSize =  1.6F;
		mParser = new parser(URL);
		mUser = new UserInfo();
		mTask = new TaskGetHtml();
	}
    @SuppressWarnings("deprecation")
	void getRevolution(){
    	Point size = new Point();
    	WindowManager w = getWindowManager();
	    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
	          w.getDefaultDisplay().getSize(size);
	          width = size.x;
	          height = size.y; 
        }else{
          Display d = w.getDefaultDisplay(); 
          width = d.getWidth(); 
          height = d.getHeight(); 
       }
    }
	Bitmap loadBitmapAssert(final String url){
		try {
			InputStream is = mContext.getAssets().open(url);
			Bitmap emo = BitmapFactory.decodeStream(is);
			is.close();
			return emo;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			toast("cannot load image assets" + url);
			return null;
		}
	}
	ProgressDialog createProgress(Context mContext){
		 ProgressDialog progressDialog = new ProgressDialog(this);
	     progressDialog.setCancelable(false);
	     progressDialog.setMessage("Loading data......");
	     progressDialog.show();
	     return progressDialog;
	}
	class TaskGetHtml extends AsyncTask<Integer, Void, Integer>{
		ProgressDialog mProgress;
		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			switch (params[0]) {
			case TASK_GETDOC:
				doc = mParser.getDoc();
				break;
			case TASK_LOGIN:
				doc = mParser.login(mUser);
				break;
			case TASK_LOGOUT:
				doc = mParser.Logout();
				break;	
			default:
				break;
			}
			
			return params[0];
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mProgress.dismiss();
			Parser();
			
			switch (result) {
			case TASK_LOGIN:
				toast("Login OK");
				break;
			default:
				break;
			}
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mProgress = createProgress(mContext);
		}
	}
	void Parser(){
		
	}
	void log(String ss){
		Log.d("nna",ss);
	}
	void toast(String ss){
		Toast.makeText(mContext	,ss, Toast.LENGTH_SHORT).show();
	}
	void toast(String ss,int time){
		if(time==0)		
			Toast.makeText(mContext	,ss, Toast.LENGTH_SHORT).show();
		else 			
			Toast.makeText(mContext	,ss, Toast.LENGTH_LONG).show();
	}
	void toast(String ss,int time, int type){
		Toast to;
		if(time==0)				to = Toast.makeText(mContext,ss, Toast.LENGTH_SHORT);
		else 					to = Toast.makeText(mContext,ss, Toast.LENGTH_LONG);
		if( type == 0)			to.setGravity(Gravity.TOP, 0, 0);
		else if(type == 1 )		to.setGravity(Gravity.CENTER, 0, 0);
		else if(type == 2)		to.setGravity(Gravity.BOTTOM, 0, 0);
		to.show();
	}
     String parsePage(int type){
    	Element elePage = doc.select("div[class=pagenav").first();
    	String mIndexPage,temp = null,m_url;
    	int curPage,lastPage;
    	if(elePage!=null){
			mIndexPage = elePage.select("td[class=vbmenu_control]").text();
    		curPage = Integer.parseInt(mIndexPage.split(" ")[1]);
    		lastPage = Integer.parseInt(mIndexPage.split(" ")[3]);
    		m_url = mParser.getUrl();
    		if(m_url.contains("&page=") != true){
    			m_url = m_url.concat("&page=1");
    		}
    		switch (type) {
			case GO_INDEXPAGE:
				temp = mIndexPage;
				break;
			case GO_FIRST:
				temp = m_url.split("&page")[0];
				break;
			case GO_NEXT:
				temp = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage+1));
				break;
			case GO_PREVIOUS:
				temp = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage-1));
	    		if(temp.contains("&page=0")){
	    			temp = temp.split("&page")[0];
	    		}
	    		break;
			case GO_LAST:
	    		temp = m_url.split("&page")[0];
	    		temp = temp.concat("&page=" + String.valueOf(lastPage));
	    		break;
			case GO_REFRESH:
				temp = m_url;
				break;
			}
    		return temp;
    	}else
    		return null;

    }
	void initUI(){
		mContext = this;
		mActivity = this;
		mMenuFont = (ImageButton)findViewById(R.id.menu_font);
		mMenuLogin = (ImageButton)findViewById(R.id.menu_login);
		mMenuTitle = (TextView)findViewById(R.id.menu_title);
		mMenuFont.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				alertFont();
			}
		});
		mMenuLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertLogin();
			}
		});
	}
	protected Dialog alertFont(){
		final Dialog dialog = new Dialog(mContext);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.setfont);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
	    lp.copyFrom(dialog.getWindow().getAttributes());
	    lp.width = WindowManager.LayoutParams.FILL_PARENT;
	    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		dialog.getWindow().setAttributes(lp);
		final TextView text1 = (TextView)dialog.findViewById(R.id.alert_txt1);
		text1.setGravity(Gravity.CENTER);
		SeekBar sb = (SeekBar)dialog.findViewById(R.id.alert_seekbar);
		sb.setMax(30);
		sb.setProgress((int)(30*(mTextSize-FONTSCALE_MIN)/
				(FONTSCALE_MAX-FONTSCALE_MIN)));
		text1.setText(String.valueOf(sb.getProgress()));
	    sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
	        public void onProgressChanged(SeekBar seekBar, int progress, 
	        		boolean fromUser){
	        	text1.setText(String.valueOf(progress));
	        	mTextSize = (float)((FONTSCALE_MAX-FONTSCALE_MIN)/
	        			(30-0)*(progress) + FONTSCALE_MIN);
	        	updateSetFont(mTextSize);
	        	
	        }
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
	    });
		dialog.show();
		return dialog;
	}
	
	protected void updateSetFont(float value){
		
	}
	protected Dialog alertLogin(){
		final Dialog dialog = new Dialog(mContext);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.login);
		final EditText edit1 = (EditText)dialog.findViewById(R.id.alert_edit1);
		final EditText edit2 = (EditText)dialog.findViewById(R.id.alert_edit2);
		TextView textTitle = (TextView)dialog.findViewById(R.id.alert_title);
		TextView text1 = (TextView)dialog.findViewById(R.id.alert_txt1);
		TextView text2 = (TextView)dialog.findViewById(R.id.alert_txt2);
		Button buttonOK = (Button)dialog.findViewById(R.id.alert_ok);
		final boolean isLogin;
		if(mUser.isLogin()){
			isLogin = true;
			textTitle.setText("LogOut");
			edit1.setVisibility(View.GONE);
			edit2.setVisibility(View.GONE);
			text1.setText("UserName:"+mUser.User());
			text2.setVisibility(View.GONE);
		}else{
			isLogin = false;
			textTitle.setText("LogIn");
			edit1.setVisibility(View.VISIBLE);
			edit2.setVisibility(View.VISIBLE);
			text2.setVisibility(View.VISIBLE);
			text1.setText("UserName:");
			edit1.setText("hidden1611");
			edit2.setText("thuonghanh");
		}
		
		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				if(!isLogin){
					toast("Click OK"+edit1.getText()+";"+edit2.getText());
					mUser.add(edit1.getText().toString(), edit2.getText().toString());
					mTask.execute(TASK_LOGIN);
				}else{
					mUser.add(edit1.getText().toString(), edit2.getText().toString());
					mTask.execute(TASK_LOGOUT);
				}
				dialog.dismiss();
			}
		});
		dialog.show();
		return dialog;
	    
	}

  
}
